package com.chookss.tiku

import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.chookss.R
import com.chookss.Urls
import com.chookss.tiku.entity.Subject
import com.chookss.tools.ClearMoreZeroUtil
import com.chookss.tools.MyToast
import com.chookss.tools.Utils
import com.chookss.view.LianxiDialog
import com.chookss.view.RecycleViewDivider
import com.chookss.view.listener.ShareDialogListener
import com.johnrambo.ktea.ktExtends.observe
import errorToast
import kotlinx.android.synthetic.main.activity_practice_test_base.*
import kotlinx.android.synthetic.main.view_subject.*
import java.util.*
import kotlin.collections.HashMap


/**   智能题库 专项练习 页面   只有提醒选择和记忆曲线
 */
class PracticeTestActivity : BasePracticeTestActivity<PracticeTestViewModel>() {
    var subjectAdapter: TitleAdapter? = null
    var memoryAdapter: TitleAdapter? = null
    var pmKey: String = ""
    var pmKeyBeiti: String = ""
    var todayInt: Int = 0
    var needStopTime: Int = 0
    private val subjectList = ArrayList<HashMap<String, String>>()
    private val memoryList = ArrayList<HashMap<String, String>>()
    var selectSubject = ArrayList<String>()
    var selectMemory = ArrayList<String>()
    var beitiType: Boolean = false  //是否背题模式
    private val mHander: Handler = Handler()
    private var mCount = 0//单个题记录时间
    var drawable: Drawable? = null
    private val mCounter: Runnable = object : Runnable {
        override fun run() {
            mCount++
            if (needStopTime <= 1) {
                tvSubjectNext.text = "下一题"
                needStopTime = 0
            } else {
                tvSubjectNext.text = "跳过(" + needStopTime + "S)"
                needStopTime--
            }

            tvTopBarRight.text = Utils.changeSeconds(mCount)
            mHander.postDelayed(this, 1000)
        }
    }

    override fun createViewModel(): PracticeTestViewModel {
        return ViewModelProviders.of(this).get(PracticeTestViewModel::class.java).apply {
            catalogCodes = intent?.getStringExtra("catalogCodes") ?: ""
            practiceType = intent?.getStringExtra("practiceType") ?: ""
            memoryLvl = ""
            subjectTypeCode = ""
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sourceType = intent.getStringExtra("practiceType").toString()
        drawable = resources.getDrawable(R.drawable.icon_ks_mb)
        drawable?.setBounds(0, 0, Utils.dip2px(this, 15f), Utils.dip2px(this, 17f)) //此为必须写的
        tvActivityTitle.text = if (viewModel.practiceType == "1") "智能题库" else "专项练习"
        if (subjectView != null) {
            subjectView?.showSubmit = true
        }

        getSameDayPracticeNum()
        topBar.visibility = View.VISIBLE
        topBar.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            var pmKeys: String = ""
            if (beitiType) {
                pmKeys = pmKeyBeiti
            } else {
                pmKeys = pmKey
            }
            if (Utils.isNull(pmKeys)) {
                LianxiDialog(this, "今日暂无答题记录",
                    ShareDialogListener {
                    }).show()
                return@setOnClickListener
            }
            var intent = Intent(this, ExamResultActivitys::class.java)
            if (beitiType) {
                intent.putExtra("pmKey", pmKeys)
                intent.putExtra("recordType", "5")
            } else {
                intent.putExtra("pmKey", pmKeys)
                intent.putExtra("recordType", sourceType)
            }
            intent.putExtra("type", 2)
            startActivity(intent)
        }
        tvBeiti.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            if (beitiType) {
                beitiType = false
                tvBeiti.isSelected = false
                mCount = 0
                MyToast.show("退出背题模式")
                tvSubjectNext.text = "下一题"
                subjectView().showSubjectNext = 1
                tvTopBarRight.setCompoundDrawables(null, null, null, null)
                getSameDayPracticeNum()
                mHander.removeCallbacks(mCounter);
                isShowAnswer = false
                gotoSubject(subjectIndex + 1)
//                if (subjectView != null) {
//                    if (subjectView.subject != null) {
//                        subjectView().hiddeAnswerDetail()
//                    }
//                }
            } else {
                beitiType = true
                tvBeiti.isSelected = true
                mCount = 0
                needStopTime = Utils.changeNumber(subjectView().subject?.needStopTime)
                tvTopBarRight.setCompoundDrawables(drawable, null, null, null)
                mHander.post(mCounter)
                MyToast.show("进入背题模式")
                subjectView().showSubjectNext = 5
                toRecite(true)
                if (!isShowAnswer) {
                    submitMyAnswer(true)
                }
            }

        }
        ivNext.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            if (beitiType) {
                isShowAnswer = false
                toRecite(false)
                mCount = 0
                gotoSubject(subjectIndex + 1)
            } else {
                if (isShowAnswer) {
                    isShowAnswer = false
                    gotoSubject(subjectIndex + 1)
                } else {
                    if (subjectView.myAnswers.size > 0) {
                        submitMyAnswer(false)
                    } else {
                        MyToast.show("请先答题，再提交")
                    }
                }
            }
        }
        tvSubjectNext.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            if (beitiType) {
                toRecite(false)
                isShowAnswer = false
                mCount = 0
                gotoSubject(subjectIndex + 1)
            } else {
                if (isShowAnswer) {
                    isShowAnswer = false
                    gotoSubject(subjectIndex + 1)
                } else {
                    if (subjectView.myAnswers.size > 0) {
                        submitMyAnswer(false)
                    } else {
                        MyToast.show("请先答题，再提交")
                    }
                }
            }
        }
        subjectView().showSubjectNext = 1
        ivSubjectShaixuan.visibility = View.VISIBLE
        ivMemory.visibility = View.VISIBLE

        llFloatBtns.visibility = View.VISIBLE
        tvBeiti.visibility = View.VISIBLE
        tvError.visibility = View.VISIBLE
        tvCollect.visibility = View.VISIBLE
        tvShare.visibility = View.VISIBLE

//        ivNext.visibility = View.VISIBLE
        initRvs()
    }

    private fun initRvs() {
//
//        ivSubjectShaixuan.setOnClickListener {
//            rlType.visibility = View.VISIBLE
//            rvSubject.visibility = View.VISIBLE
//        }
//        ivMemory.setOnClickListener {
//            rlType.visibility = View.VISIBLE
//            rvMemory.visibility = View.VISIBLE
//        }
//        rlType.setOnClickListener {
//            rlType.visibility = View.GONE
//            rvSubject.visibility = View.GONE
//            rvType.visibility = View.GONE
//            rvMemory.visibility = View.GONE
//        }
        rvSubject.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvSubject.addItemDecoration(
            RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(
                    R.color.line_gray
                )
            )
        )
        rvMemory.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvMemory.addItemDecoration(
            RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), resources.getColor(
                    R.color.line_gray
                )
            )
        )
        val map: HashMap<String, String> = HashMap()
        map.put("title", "单选题")
        map.put("data", "1001")
        map.put("select", "false")
        subjectList.add(map)
        val map2: HashMap<String, String> = HashMap()
        map2.put("title", "多选题")
        map2.put("data", "1002")
        map2.put("select", "false")
        subjectList.add(map2)
        val map3: HashMap<String, String> = HashMap()
        map3.put("title", "判断题")
        map3.put("data", "1003")
        map3.put("select", "false")
        subjectList.add(map3)
        val map4: HashMap<String, String> = HashMap()
        map4.put("title", "填空题")
        map4.put("data", "1004")
        map4.put("select", "false")
        subjectList.add(map4)
        val map5: HashMap<String, String> = HashMap()
        map5.put("title", "问答题")
        map5.put("data", "1005")
        map5.put("select", "false")
        subjectList.add(map5)
        val memoryMap: HashMap<String, String> = HashMap()
        memoryMap.put("title", "未记忆")
        memoryMap.put("data", "01")
        memoryMap.put("select", "false")
        memoryList.add(memoryMap)
        val memoryMap2: HashMap<String, String> = HashMap()
        memoryMap2.put("title", "开始记忆")
        memoryMap2.put("data", "02")
        memoryMap2.put("select", "false")
        memoryList.add(memoryMap2)
        val memoryMap3: HashMap<String, String> = HashMap()
        memoryMap3.put("title", "正在巩固")
        memoryMap3.put("data", "03")
        memoryMap3.put("select", "false")
        memoryList.add(memoryMap3)
        val memoryMap4: HashMap<String, String> = HashMap()
        memoryMap4.put("title", "已牢记")
        memoryMap4.put("data", "04")
        memoryMap4.put("select", "false")
        memoryList.add(memoryMap4)
        val memoryMap5: HashMap<String, String> = HashMap()
        memoryMap5.put("title", "开始遗忘")
        memoryMap5.put("data", "05")
        memoryMap5.put("select", "false")
        memoryList.add(memoryMap5)
        val memoryMap6: HashMap<String, String> = HashMap()
        memoryMap6.put("title", "已遗忘")
        memoryMap6.put("data", "06")
        memoryMap6.put("select", "false")
        memoryList.add(memoryMap6)
        subjectAdapter = TitleAdapter(R.layout.item_subject_choice, this, subjectList)
        rvSubject.setAdapter(subjectAdapter)
        memoryAdapter = TitleAdapter(R.layout.item_subject_choice, this, memoryList)
        rvMemory.setAdapter(memoryAdapter)
        subjectAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (subjectList.get(position).get("select").equals("true")) {
                subjectList.get(position).put("select", "false")
                selectSubject.remove(subjectList.get(position).get("data"));
            } else {
                subjectList.get(position).put("select", "true")
                selectSubject.add(subjectList.get(position).get("data").toString())
            }
            var subjectTypeCode: String? = null
            for (i in 0 until selectSubject.size) {
                if (i == 0) {
                    subjectTypeCode = selectSubject.get(i)
                } else {
                    subjectTypeCode = subjectTypeCode + "," + selectSubject.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            println(subjectTypeCode.toString())
            viewModel.subjectTypeCode = subjectTypeCode.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex)
            rlType.visibility = View.GONE
            rvSubject.visibility = View.GONE
            if (selectSubject.size > 0) {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_sel)
            } else {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_unsel)
            }
        }
        memoryAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (memoryList.get(position).get("select").equals("true")) {
                memoryList.get(position).put("select", "false")
                selectMemory.remove(memoryList.get(position).get("data"));
            } else {
                memoryList.get(position).put("select", "true")
                selectMemory.add(memoryList.get(position).get("data").toString())
            }
            var memoryLvl: String? = null
            for (i in 0 until selectMemory.size) {
                if (i == 0) {
                    memoryLvl = selectMemory.get(i)
                } else {
                    memoryLvl = memoryLvl + "," + selectMemory.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            viewModel.memoryLvl = memoryLvl.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex)
            rlType.visibility = View.GONE
            rvMemory.visibility = View.GONE
            if (selectMemory.size > 0) {
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_sel)
            } else {
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_unsel)
            }
        }
    }

    private fun getSameDayPracticeNum() {
        viewModel.getSameDayPracticeNum().observe(this, {
            if (it.error != null) {
                errorToast(it.error.message ?: "")
            } else if (it.data != null) {
                if (!beitiType) {
                    todayInt = Utils.changeNumber(it.data.totalNum.toString())
                    pmKey = it.data.recordUid
                    tvTopBarLeft.text = "今日练习: ${it.data.totalNum}题"
                    tvTopBarRight.text =
                        "正确率: ${ClearMoreZeroUtil.subZeroAndDot(it.data.rightRatio)}%"
                }
            }
        })
    }

    private fun toRecite(isFirst: Boolean) {
        if (subjectView != null) {
            if (subjectView.subject == null) {
                return
            }
            viewModel.toRecite(subjectView.subject!!, mCount, isFirst).observe(this, {
                if (it.error != null) {
                    errorToast(it.error.message ?: "")
                } else if (it.data != null) {
                    pmKeyBeiti = it.data.recordUid
                    tvTopBarLeft.text = "今日已背题: ${it.data.totalNum}题"
                }
            })
        }

    }

    override fun onAnswerSubmited(subjectIndex: Int, subject: Subject, myAnswers: List<String>) {
        super.onAnswerSubmited(subjectIndex, subject, myAnswers)
        getSameDayPracticeNum()
    }

    override fun onShowSubjectsLoaded(isShowData: Boolean) {
        if (isShowData) {
            ivSubjectShaixuan.visibility = View.VISIBLE
            ivMemory.visibility = View.VISIBLE
            llFloatBtns.visibility = View.VISIBLE
            subjectScrollView.visibility = View.VISIBLE
            topBar.visibility = View.VISIBLE
//            ivNext.visibility = View.VISIBLE
            llEmpty.visibility = View.GONE
            if (beitiType) {
                needStopTime = Utils.changeNumber(subjectView().subject?.needStopTime)
                submitMyAnswer(true)
            }
        } else {
            if (viewModel.subjectPageMap.size > 1) {
                MyToast.show("已经是最后一题了")
//                subjectIndex = 0;
//                gotoSubject(subjectIndex)
            } else {
                llFloatBtns.visibility = View.INVISIBLE
                subjectScrollView.visibility = View.INVISIBLE
                topBar.visibility = View.INVISIBLE
                ivNext.visibility = View.INVISIBLE
                llEmpty.visibility = View.VISIBLE
                tvEmptyView1.text = "暂无题目"
                tvEmptyView2.text = ""
            }
        }

    }

    override fun initData() {

    }

    class TitleAdapter(
        layoutResId: Int,
        context: Context,
        data: ArrayList<HashMap<String, String>>
    ) : BaseQuickAdapter<HashMap<String, String>, BaseViewHolder>(layoutResId, data) {

        override fun convert(holder: BaseViewHolder, item: HashMap<String, String>) {
            val ivStatus = holder?.getView<ImageView>(R.id.ivStatus)
            val tvTiltle = holder?.getView<TextView>(R.id.tvTiltle)
            tvTiltle?.text = item?.get("title")
            if (item?.get("select").equals("true")) {
                tvTiltle?.isSelected = true
                ivStatus?.isSelected = true
            } else {
                tvTiltle?.isSelected = false
                ivStatus?.isSelected = false
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        if (mHander != null) {
            mHander.removeCallbacks(mCounter);
        }
    }

}